import { useEffect, useRef, useState } from "react";
import { Progress } from "antd";
import * as pdfjsLib from "pdfjs-dist";
import { PDFViewer, PDFLinkService, EventBus } from "pdfjs-dist/web/pdf_viewer";
import "pdfjs-dist/web/pdf_viewer.css";
import styles from "./index.module.less";

function App(props) {
  const [workerSrc, setWorkerSrc] = useState();
  const [percent, setPercent] = useState(0);
  let prePercent = 0;
  const [totalPages, setTotalPages] = useState(0);

  let padfLoadingTask = null;
  const { fileUrl } = props;
  useEffect(() => {
    import("pdfjs-dist/build/pdf.worker.entry").then((module) => {
      pdfjsLib.GlobalWorkerOptions.workerSrc = module.default;
      setWorkerSrc(module.default);
      initPdfView();
    });
  }, [fileUrl]);
  // pdfView自动缩放
  const autoScale = (viewer) => {
    // 缩放模式: "page-fit" ,"auto" ,"page-width"
    viewer.currentScaleValue = "page-width";
  };

  // 监听pdfView外部容器变化，主要是配合自动缩放
  const onResize = (viewer) => {
    const resizeObserver = new ResizeObserver((entries) => {
      // 创建观察对象
      autoScale(viewer); // entries[0].contentRect
    });
    resizeObserver.observe(containerRef.current); // 指定要观察的dom
  };

  const containerRef = useRef(null);

  // 初始化pdfView
  const initPdfView = () => {
    if (!fileUrl) {
      return;
    }
    const linkService = new PDFLinkService();
    const eventBus = new EventBus();
    eventBus.on("pagesinit", (e) => {
      onResize(e.source); // 同一次轮回 是拿不到view的，所以只能通过e.source取出
    });
    const newViewer = new PDFViewer({
      container: containerRef.current, // 显示PDF的容器dom
      linkService,
      eventBus,
      textLayerMode: 2,
      renderer: "canvas",
    });
    linkService.setViewer(newViewer);
    padfLoadingTask = pdfjsLib.getDocument({ url: fileUrl });
    padfLoadingTask.promise.then(
      (pdf) => {
        linkService.setDocument(pdf);
        newViewer.setDocument(pdf);
        setTotalPages(pdf.numPages);
      },
      (error) => {
        console.error("pdf加载失败", error);
      }
    );
    padfLoadingTask.onProgress = (data) => {
      const percentTemp = Math.round((data.loaded / data.total) * 100);
      if (
        (percentTemp >= prePercent && percentTemp % 5 == 0) ||
        percentTemp >= 100
      ) {
        prePercent = percentTemp;
        setPercent(percentTemp);
      }
    };
  };

  return (
    <>
      <div className={styles.loadingProgressWrap}>
        <Progress percent={percent} className={styles.loadingProgress} />
        <span>共{totalPages}页</span>
      </div>

      <div ref={containerRef} className={styles.container}>
        <div id="viewer" className={styles.pdfViewer}></div>
      </div>
    </>
  );
}

export default App;
